package com.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JDBCUtil02 {
    private static String DRIVER;//（大写）业内规则：不再修改
    private static String URL;
    private static String USERNAME;
    private static String PASSWORD;
    private static ResultSet rs=null;
    private static PreparedStatement ps=null;
    private static Connection connection=null;
    //读取配置文件  为了保证读取一次  写在静态代码块中
    static {
        try {
            Properties properties = new Properties();
            InputStream is = JDBCUtil02.class.getClassLoader().
                    getResourceAsStream("mysql.properties");
            properties.load(is);
            //对上面的变量赋值只需要执行一次
            DRIVER=properties.getProperty("driver");
            URL=properties.getProperty("url");
            USERNAME=properties.getProperty("username");
            PASSWORD=properties.getProperty("password");
            Class.forName(DRIVER);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //获取连接的方法
    public static Connection getConnection() throws Exception {
        connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        return connection;
    }
    //查询所有
    public static ResultSet selectALL(String sql)throws Exception{
        ps = getConnection().prepareStatement(sql);
       rs = ps.executeQuery();
        return rs;
    }
    //按条件查询
    public static ResultSet select(String sql,String...str)throws Exception{
        ps = getConnection().prepareStatement(sql);
        //传参
        for (int i = 0; i < str.length; i++) {
            ps.setString(i+1,str[i]);
        }
        rs = ps.executeQuery();
        return rs;
    }
    //关闭
    public static void closeALL()throws Exception{
        rs.close();
        ps.close();
        connection.close();
    }
}
